import { useEffect, useState } from "react";
import "./index.scss";
import classNames from "classnames";
function XtxPagination({
  total,
  pageSize = 10,
  btnCount = 5,
  currentPage,
  emit,
}: {
  total: number;
  pageSize?: number;
  btnCount?: number;
  currentPage: number;
  emit: (proname: string, value: number) => void;
}) {
  const [mytotals, setTotals] = useState(0);
  const [mycurrent, setCurrent] = useState(0);
  const [mypageSizeS, setPageSize] = useState(0);
  const [mybtnCounts, setBtnCount] = useState(0);
  useEffect(() => {
    setTotals(total);
    setCurrent(currentPage);
    setBtnCount(btnCount);
    setPageSize(pageSize);
  }, [total, currentPage, btnCount, pageSize]);
  const pageRender = () => {
    const pageCount = Math.ceil(mytotals / mypageSizeS);
    let start = mycurrent - Math.floor(mybtnCounts / 2);
    let end = start + mybtnCounts - 1;
    if (start < 1) {
      start = 1;
      end =
        start + mybtnCounts - 1 > pageCount
          ? pageCount
          : start + mybtnCounts - 1;
    }
    if (end >= pageCount) {
      end = pageCount;
      start = end - mybtnCounts + 1 < 1 ? 1 : end - mybtnCounts + 1;
    }
    const list = [];
    for (let i = start; i <= end; i++) {
      list.push(i);
    }
    return { pageCount, list, start, end };
  };

  const changePage = function (newPage: number) {
    if (mycurrent !== newPage) {
      setCurrent(newPage);
      //   emit事件
      emit("current-change", newPage);
    }
  };
  return (
    <div className="xtx-pagination">
      {mycurrent <= 1 ? (
        <a href="javascript:;" className="disabled">
          上一页
        </a>
      ) : (
        <a href="javascript:;" onClick={() => changePage(mycurrent - 1)}>
          上一页
        </a>
      )}
      {pageRender().start > 1 && <span>...</span>}

      {pageRender().list.map((item) => (
        <a
          href="javascript:;"
          className={classNames({ active: item === mycurrent })}
          onClick={() => changePage(item)}
        >
          {item}
        </a>
      ))}
      {pageRender().end < pageRender().pageCount && <span>...</span>}
      {mycurrent >= pageRender().pageCount ? (
        <a v-if="" href="javascript:;" className="disabled">
          下一页
        </a>
      ) : (
        <a href="javascript:;" onClick={() => changePage(mycurrent + 1)}>
          下一页
        </a>
      )}
    </div>
  );
}
export default XtxPagination;
